package com.lemon.smartsafetynew.ui.activity.me;

import android.content.Intent;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.AesEncryptor;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.ui.activity.user.UserLoginActivity;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/10/19.
 */

public class ChangePasswordActivity extends SwipeBackActivity {

    @Bind(R.id.old_password_edit)
    EditText oldPasswordEdit;
    @Bind(R.id.old_password_eye)
    ImageView oldPasswordEye;
    @Bind(R.id.new_password_edit)
    EditText newPasswordEdit;
    @Bind(R.id.new_password_eye)
    ImageView newPasswordEye;
    @Bind(R.id.new_password_twice_edit)
    EditText newPasswordTwiceEdit;
    @Bind(R.id.new_password_twice_eye)
    ImageView newPasswordTwiceEye;


    private MaterialDialog materialDialog;


    @Override
    protected void initTitle() {
        this.setBarTitle("修改密码");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(ChangePasswordActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_change_password;
    }

    private boolean checkOldPassword(String oldPassword) {
        return !(null == oldPassword || "".equals(oldPassword));
    }

    private boolean checkPassword(String password) {
        return !(null == password || "".equals(password));
    }

    private boolean matcherPassword(String password) {

        String pattern = SafeCloudConstants.PASSWORD_CHECK;
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(password);

        return mMatcher.matches();
    }

    private boolean checkRetypePassword(String retypePassword) {
        return !(null == retypePassword || "".equals(retypePassword));
    }

    private boolean equalRetypePassword(String password, String retypePassword) {
        return password.equals(retypePassword);
    }

    @OnClick({R.id.old_password_eye, R.id.new_password_eye, R.id.new_password_twice_eye, R.id.submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.old_password_eye:

                oldPasswordEye.setSelected(!oldPasswordEye.isSelected());
                if (oldPasswordEye.isSelected()) {
                    oldPasswordEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    oldPasswordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.new_password_eye:

                newPasswordEye.setSelected(!newPasswordEye.isSelected());
                if (newPasswordEye.isSelected()) {
                    newPasswordEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    newPasswordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.new_password_twice_eye:

                newPasswordTwiceEye.setSelected(!newPasswordTwiceEye.isSelected());
                if (newPasswordTwiceEye.isSelected()) {
                    newPasswordTwiceEdit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    newPasswordTwiceEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

                break;
            case R.id.submit_btn:

                String oldPassword = oldPasswordEdit.getText().toString().trim();
                String password = newPasswordEdit.getText().toString().trim();
                String retypePassword = newPasswordTwiceEdit.getText().toString().trim();

                if (checkOldPassword(oldPassword)) {

                    if (checkPassword(password) && matcherPassword(password)) {

                        if (checkRetypePassword(retypePassword) && equalRetypePassword(password, retypePassword)) {

                            LemonRequestParams params = new LemonRequestParams("");
                            params.put("password", AesEncryptor.encrypt(oldPassword));
                            params.put("newPassword", AesEncryptor.encrypt(password));
                            params.put("confirmPassword", AesEncryptor.encrypt(retypePassword));

                            AccountServices
                                    .init()
                                    .modifyAccountPassword(params);

                        } else {
                            mHUDUtil.showErrorTip(getString(R.string.retype_password_error));
                        }

                    } else {
                        mHUDUtil.showErrorTip(getString(R.string.password_format_error));
                    }
                } else {
                    mHUDUtil.showErrorTip(getString(R.string.old_password_can_not_null));
                }


                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_MODIFIED_PASSWORD.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    unbindJPush();   //解绑并退出
                } else {
                    mHUDUtil.showDoneTip(event.getMsg());
                }
            }
        } else if(KeyConstants.URL_UNBIND_JPUSH_CHANGE_PASSWORD.equals(event.getTag())) {                           //解绑JPush
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip("修改密码成功", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            doExist();
                        }
                    });
                }
            }
        }

    }

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(ChangePasswordActivity.this)
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        cancelDialog();
    }


    private void doExist() {
        AccountUtil.userLogout();
        Intent mIntent = new Intent(ChangePasswordActivity.this, UserLoginActivity.class);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mIntent);
    }


    /**
     * 解绑
     */
    private void unbindJPush() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        AccountServices.init().unbindJPush(params, KeyConstants.URL_UNBIND_JPUSH_CHANGE_PASSWORD);
    }
}
